package org.jeecg.common.util.sm.utils;

import cn.hutool.core.codec.Base64Encoder;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.security.NoSuchProviderException;
import java.security.PublicKey;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

public class CertUtils {


    static final String BEGIN = "-----BEGIN CERTIFICATE-----\n";
    static final String END = "\n-----END CERTIFICATE-----";

    public static X509Certificate loadCertificate(String content) {
        StringBuilder certSb = new StringBuilder();
        if (!content.contains(BEGIN)) {
            certSb.append(BEGIN);
        }
        certSb.append(content);
        if (!content.contains(END)) {
            certSb.append(END);
        }
        try (ByteArrayInputStream bis = new ByteArrayInputStream(certSb.toString().getBytes())) {
            CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");
            return (X509Certificate) cf.generateCertificate(bis);
        } catch (IOException | CertificateException | NoSuchProviderException e) {
            e.printStackTrace();
            return null;
        }
    }


    public static String getPublicKeyStr(String content) {
        PublicKey publicKey = getPublicKey(content);

        if (publicKey == null) {
            return "";
        }
        return Base64Encoder.encode(publicKey.getEncoded());
    }

    public static PublicKey getPublicKey(String content) {
        PublicKey result = null;
        try {
            X509Certificate x509Certificate = loadCertificate(content);
            result = x509Certificate.getPublicKey();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }
}
